package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;

import java.util.List;

/**
 * @description: TODO
 * @author: wazi
 * @time: 2021/1/4 19:46
 */
public class UserUtil {

    /**
     *  根据人员ID查询所在的父部门ID 返回一个数组
     * @param userId
     * @param token
     * @return
     */
    public static JSONArray listParentDepts(String userId,String token){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list_parent_depts");
        OapiDepartmentListParentDeptsRequest req = new OapiDepartmentListParentDeptsRequest();
        req.setUserId(userId);
        req.setHttpMethod("GET");
        OapiDepartmentListParentDeptsResponse rsp = null;
        try {
            rsp = client.execute(req, token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        JSONObject obj = JSON.parseObject(rsp.getBody());
        JSONArray jsonArray = obj.getJSONArray("department");
        return jsonArray;
    }

    /**
     *  获取部门详情 返回名称
     * @param depId
     * @param accessToken
     * @return
     */
    public static String searchDept(String depId,String accessToken){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
            OapiDepartmentGetRequest req = new OapiDepartmentGetRequest();
            req.setId(depId);
            req.setHttpMethod("GET");
            OapiDepartmentGetResponse rsp = client.execute(req, accessToken);
            String name = JSON.parseObject(rsp.getBody()).getString("name");
            return name;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获取部门下的子部门ID列表 只查询到下一级
    public static JSONArray getSubDept(String depId,String accessToken){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.setDeptId(Long.parseLong(depId));
            OapiV2DepartmentListsubidResponse rsp = client.execute(req, accessToken);
            return JSON.parseObject(rsp.getBody()).getJSONObject("result").getJSONArray("dept_id_list");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 查询该部门下的子部门Id 包括所有子部门
    public static List getSubDepts(String depId,String accessToken,List<String> deptList) {
        JSONArray subDept = getSubDept(depId, accessToken);
        if(subDept != null && subDept.size() > 0){
            List<String> depts = subDept.toJavaList(String.class);
            deptList.addAll(depts);
            for (String dept : depts) {
                getSubDepts(dept,accessToken,deptList);
            }
        }
        return deptList;
    }

    /**
     * 获取用户详情
     *
     * @param accessToken
     * @param userId
     * @return OapiUserGetResponse
     */
    public static JSONObject getUserProfile(String accessToken, String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
            return JSON.parseObject(rsp.getBody()).getJSONObject("result");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
}

    /**
     * 获取企业角色列表
     * @param accessToken
     * @return
     */
    public static OapiRoleListResponse getRoleList(String accessToken){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/list");
            OapiRoleListRequest req = new OapiRoleListRequest();
            req.setSize(200L);
            req.setOffset(0L);
            OapiRoleListResponse rsp = client.execute(req, accessToken);
            return rsp;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取角色的员工列表
     * @param accessToken
     * @return
     */
    public static OapiRoleSimplelistResponse getRoleSimplelist(String accessToken,long roleId){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/simplelist");
            OapiRoleSimplelistRequest req = new OapiRoleSimplelistRequest();
            req.setRoleId(roleId);
            OapiRoleSimplelistResponse rsp = client.execute(req, accessToken);
            return rsp;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  获取指定角色的员工ID
     * @param accessToken
     * @param roleGroupName
     * @param roleName
     * @return
     */
    public static String getRoleUserId(String accessToken,String roleGroupName,String roleName){
        List<OapiRoleListResponse.OpenRoleGroup> list = getRoleList(accessToken).getResult().getList();
        long roleId = 0L;
        for (OapiRoleListResponse.OpenRoleGroup openRoleGroup : list) {
            if (openRoleGroup.getName().equals(roleGroupName)){
                for (OapiRoleListResponse.OpenRole role : openRoleGroup.getRoles()) {
                    if(role.getName().equals(roleName)){
                        roleId = role.getId();
                        String userid = getRoleSimplelist(accessToken, roleId).getResult().getList().get(0).getUserid();
                        return userid;
                    }
                }
            }
        }
        return null;
    }

    public static List<String> getUserIds(String dept, String accessToken) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
        OapiUserListidRequest req = new OapiUserListidRequest();
        req.setDeptId(Long.valueOf(dept));
        OapiUserListidResponse rsp = client.execute(req, accessToken);
        System.out.println(rsp.getBody());
        return rsp.getResult().getUseridList();
    }
}
